<template>
	<view class="content">
		<view class="nav-container">
			<u-navbar :fixed="false" color="#333333" background-color="#FFFFFF" :autoBack="true">
				<block slot="center">
					<picker @change="bindPickerChange" mode="selector" :range="columns" :value="index"
						range-key="title">
						<view class="form-item">
							<view>{{ getValue() }}</view>
						</view>
					</picker>
				</block>
			</u-navbar>
		</view>
		<!-- 确认驻场人员框 -->
		<u-modal title="请选择驻场人员" :show="showModal" @confirm="confirmResident()">
			<u-radio-group v-model="residentModal" placement="column" :size="32" shape="shape" activeColor="#f40016">
				<u-radio :customStyle="{ marginRight: '16rpx', marginTop: '16rpx' }"
					v-for="(item, index) in residentList" :key="index" :label="item.userName"
					:name="JSON.stringify(item)" :labelSize="32">
					<block slot="status">
						<view v-if="item.isOnline">
							<u-badge :isDot="true" type="success"></u-badge>
						</view>
						<view v-else>
							<u-badge :isDot="true" type="error"></u-badge>
						</view>
					</block>
				</u-radio>
			</u-radio-group>
		</u-modal>
		<!-- 聊天内容 -->
		<view class="scroll_container">

			<scroll-view class="chat" scroll-y="true" scroll-with-animation="true" :scroll-into-view="scrollToView">
				<view class="chat-main" :style="{ paddingBottom: inputh + 'px' }">
					<view class="chat-ls" v-for="(item, index) in unshiftmsg" :key="index" :id="'msg' + index">
						<view class="chat-time" v-if="item.date != '' && !item.inInterval">{{
            changeTime(item.date)
          }}</view>
						<view class="msg-m msg-left" v-if="item.fromId == friendName">
							<view style="
                display: flex;
                flex-direction: column;
                justify-content: center;
                align-items: center;
              ">
								<image class="user-img" :src="getAvatorSrc(item.headerUrl)"></image>
								<text class="user-name">{{ item.fromName }}</text>
							</view>
							<view class="message" v-if="item.messageType == 0">
								<!-- 文字 -->
								<view class="msg-text">{{ item.messageData }}</view>
							</view>
							<view class="message" v-if="item.messageType == 1" @tap="previewImg(item.messageData)">
								<!-- 图像 -->
								<image :src="item.messageData" class="msg-img" mode="widthFix"></image>
							</view>
						</view>
						<view class="msg-m msg-right" v-if="item.fromId != friendName">
							<view style="
                display: flex;
                flex-direction: column;
                justify-content: center;
                align-items: center;
              ">
								<image class="user-img" :src="getAvatorSrc(item.headerUrl)"></image>
								<text class="user-name">{{ userName }}</text>
							</view>
							<view class="message" v-if="item.messageType == 0">
								<view class="msg-text">{{ item.messageData }}</view>
							</view>
							<view class="message" v-if="item.messageType == 1" @tap="previewImg(item.messageData)">
								<image :src="item.messageData" class="msg-img" mode="widthFix"></image>
							</view>
						</view>
					</view>
				</view>
			</scroll-view>
		</view>
		<submit @inputs="inputs" @heights="heights"></submit>
	</view>
</template>

<script>
	import dateTime from "@/common/dataTime.js";
	import submit from "@/minepkg/customer_service_submit/customer_service_submit.vue";
	import _utils from "@/common/_utils.js";
	import wsRequest from "@/common/websocket.js";
	import $C from '@/common/config.js';

	export default {
		data() {
			return {
				residentList: [],
				residentModal: "",
				showModal: false,
				friendName: "",
				msg: [],
				// 反转数据接收
				unshiftmsg: [],
				imgMsg: [],
				scrollToView: "",
				oldTime: uni.$u.timeFormat(false, "yyyy-mm-dd hh:MM:ss"),
				inputh: "60",
				notSelected: true,
				columns: [],
				estateId: "",
				estateType: 2,
				project: "",
				index: 0,
				userName: "测试",
				phone: "13333333330",
				userList: [],
				newWS: {},
			};
		},
		created() {
			this.userName = uni.getStorageSync("userName");
			this.newWS = this.$Socket
			this.onMessage();
		},
		watch: {
			msg(val) {
				this.initHistory();
			},
		},
		onLoad() {
			this.estateId = uni.getStorageSync("estateId");
			this.fetchProjectList();
			this.fetchResident();
		},
		onShow() {
			this.getHistory()
			this.initHistory()
		},
		components: {
			submit,
		},
		methods: {
			getAvatorSrc(src) {
				let _url =
					src == "" ?
					"/static/mine_icons/avator.png" :
					uni.$http.baseURL + "/file/download?fileId=" + src;
				return _url;
			},
			bindPickerChange: function(e) {
				this.notSelected = false;
				this.index = e.detail.value;
				this.estateId = this.columns[this.index].estateId;
				console.log(e.detail);
				this.fetchResident();
			},
			getValue() {
				let select = this.notSelected ?
					uni.getStorageSync("selectedEstate") :
					this.columns[this.index].title;
				return select;
			},
			confirmResident() {
				console.log(this.residentModal);
				if (this.residentModal == "") {
					uni.$showMsg("请选择驻场人员！");
					return;
				} else {
					let selectedResident = JSON.parse(this.residentModal);
					if (!selectedResident.isOnline) {
						let _this = this;
						uni.showModal({
							title: "提示",
							content: "当前选中人员为离线状态",
							confirmText: "继续",
							success: function(res) {
								if (res.confirm) {
									_this.friendName = selectedResident.userId;
									_this.showModal = false;
									_this.getHistory();
								} else if (res.cancel) {
									_this.showModal = true;
								}
							},
						});
					} else {
						this.friendName = selectedResident.userId;
						this.showModal = false;
						this.getHistory();
					}
					this.residentModal = "";
				}
			},
			onMessage() {
				this.newWS.socketTask.onMessage((res) => {
					if (res.data != null && res.data != "") {
						let _result = JSON.parse(res.data);
						this.friendName = _result.fromId;
						let _len = this.unshiftmsg.length;
						if (_len > 0) {
							let x =
								new Date(_result.date) - new Date(this.unshiftmsg[_len - 1].date);
							if (x > 180000) {
								_result.inInterval = false;
							} else {
								_result.inInterval = true;
							}
						} else {
							_result.inInterval = false;
						}
						this.unshiftmsg.push(_result);
						this.goBottom()
					}
				});
			},
			async getHistory() {
				let form = _utils.backTime(3);
				form.fromUserId = this.friendName;

				const {
					data
				} = await uni.$http.post(
					uni.$http.baseURL + "/webSocket/getHistoryMessage",
					form
				);
				if (data.status == 0) {
					let _t = data.body;
					this.msg = _t.reverse();
				} else {
					// uni.$showMsg(data.message)
					uni.$showMsg("获取历史消息失败！");
				}
			},
			//获取项目列表
			async fetchProjectList() {
				let form = {
					estateType: 2,
					roleId: "3",
					userId: uni.getStorageSync("userId"),
				};
				const {
					data
				} = await uni.$http.post(
					uni.$http.baseURL + "/userEstateMap/getByQuery",
					form
				);
				let temp = [];
				if (data.status === 0) {
					for (let i = 0; i < data.body.length; i++) {
						let item = data.body[i];
						let _data = {};
						_data.title = item.businessRealEstateVO.floorName;
						_data.estateId = item.businessRealEstateVO.floorId;
						temp.push(_data);
					}
					this.columns = temp;
					console.log(this.columns);
				}
			},
			//获取驻场列表
			async fetchResident() {
				let form = {
					estateType: 2,
					estateId: this.estateId,
				};
				const {
					data
				} = await uni.$http.get(
					uni.$http.baseURL + "/getResidentInfoList",
					form
				);
				if (data.status === 0) {
					//TODO获取驻场人员Id
					if (data.body.length != 0) {
						let _residentList = data.body;
						let temp = [];
						const _userId = uni.getStorageSync("userId");
						for (let i = 0; i < _residentList.length; i++) {
							if (_residentList[i].userId != _userId) {
								temp.push(_residentList[i]);
							}
						}
						console.log(temp);
						this.residentList = temp;
						if (this.residentList.length == 0) {
							this.showModal = false;
							uni.showModal({
								title: "当前项目无驻场人员",
								content: " 请重新选择项目！",
								confirmColor: "#0bc183",
								confirmText: "知道了",
								showCancel: false,
							});
						} else {
							this.showModal = true;
						}
					} else {
						uni.showModal({
							title: "暂无在线驻场人员！",
							content: " 在线时间9:00~17:00",
							confirmColor: "#0bc183",
							confirmText: "知道了",
							showCancel: false,
						});
						// uni.$showMsg('暂无在线驻场人员！')
						this.friendName = "";
					}
				} else {
					this.showModal = false;
					uni.$showMsg(data.message);
				}
			},
			initHistory() {
				this.unshiftmsg = [];
				// 数组倒叙 主要是应对后端传过来的数据
				for (var i = 0; i < this.msg.length; i++) {
					//时间间隔处理
					if (i < this.msg.length - 1) {
						//这里表示头部时间还是显示一下
						let t = dateTime.spaceTime(this.oldTime, this.msg[i].date);
						if (t) {
							this.oldTime = t;
						}
						this.msg[i].date = t;
					}
					// 获取图片，为下面的预览做准备
					if (this.msg[i].messageType == 1) {
						this.imgMsg.unshift(this.msg[i].messageData);
					}
					this.unshiftmsg.unshift(this.msg[i]);
				}
				// 跳转到最后一条数据 与前面的:id进行对照
				this.goBottom()
			},
			changeTime(date) {
				return dateTime.dateTime1(date);
			},
			// 进行图片的预览
			previewImg(e) {
				let index = 0;
				for (let i = 0; i < this.imgMsg.length; i++) {
					if (this.imgMsg[i] == e) {
						index = i;
					}
				}
				console.log("index", index);
				// 预览图片
				uni.previewImage({
					current: index,
					urls: this.imgMsg,
					longPressActions: {
						itemList: ["保存图片"],
						success: function(data) {
							console.log(
								"选中了第" +
								(data.tapIndex + 1) +
								"个按钮,第" +
								(data.index + 1) +
								"张图片"
							);
						},
						fail: function(err) {
							console.log(err.errMsg);
						},
					},
				});
			},
			//接受输入内容
			inputs(e) {
				//时间间隔处理
				let _userId = uni.getStorageSync("userId");
				let _residentId = uni.getStorageSync("residentId");
				let _avator = uni.getStorageSync("avator");
				//时间间隔处理
				let data = {
					fromId: _userId,
					toId: this.friendName,
					isCreateConnect: false,
					headerUrl: _avator,
					messageData: e.message,
					date: uni.$u.timeFormat(false, "yyyy-mm-dd hh:MM:ss"),
					messageType: e.type,
				};
				// 发送给服务器消息
				// onSendWS(JSON.stringify(data));
				this.newWS.send(JSON.stringify(data));
				let _len = this.unshiftmsg.length;
				if (_len > 0) {
					let x = new Date(data.date) - new Date(this.unshiftmsg[_len - 1].date);
					if (x > 180000) {
						data.inInterval = false;
					} else {
						data.inInterval = true;
					}
				} else {
					data.inInterval = false;
				}
				this.unshiftmsg.push(data);
				// 跳转到最后一条数据 与前面的:id进行对照
				this.$nextTick(function() {
					this.scrollToView = "msg" + (this.unshiftmsg.length - 1);
				});
				if (e.type == 1) {
					this.imgMsg.push(e.message);
				}
				console.log(e);
			},
			//输入框高度
			heights(e) {
				console.log("高度:", e);
				this.inputh = e;
				this.goBottom();
			},
			// 滚动到底部
			goBottom() {
				this.scrollToView = "";
				this.$nextTick(function() {
					this.scrollToView = "msg" + (this.unshiftmsg.length - 1);
				});
			},
		},
	};
</script>

<style lang="scss" scoped>
	page {
		height: 100%;
	}

	.scroll_container {
		margin-top: 20rpx;
	}

	.content {
		height: 100%;
		background-color: rgba(244, 244, 244, 1);
	}

	.chat {
		// height: 100%;
		height: 100vh;

		.chat-main {
			padding-left: 32rpx;
			padding-right: 32rpx;
			padding-top: 20rpx;
			// padding-bottom: 120rpx;  //获取动态高度
			display: flex;
			flex-direction: column;
		}

		.chat-ls {
			.chat-time {
				font-size: 24rpx;
				color: rgba(39, 40, 50, 0.3);
				line-height: 34rpx;
				padding: 10rpx 0rpx;
				text-align: center;
			}

			.msg-m {
				display: flex;
				padding: 20rpx 0;

				.user-img {
					flex: none;
					width: 80rpx;
					height: 80rpx;
					border-radius: 50%;
				}

				.message {
					flex: none;
					max-width: 480rpx;
				}

				.msg-text {
					font-size: 32rpx;
					color: rgba(39, 40, 50, 1);
					line-height: 44rpx;
					padding: 18rpx 24rpx;
					word-break: break-all;
				}

				.msg-img {
					max-width: 400rpx;
					border-radius: 20rpx;
				}
			}

			.msg-left {
				flex-direction: row;

				.msg-text {
					margin-top: 30rpx;
					margin-left: 16rpx;
					background-color: #fff;
					border-radius: 0rpx 20rpx 20rpx 20rpx;
					box-shadow: 0rpx 5rpx 15rpx 0rpx rgba(0, 0, 0, 0.18);
					word-break: break-all;
				}

				.ms-img {
					margin-left: 16rpx;
				}
			}

			.msg-right {
				flex-direction: row-reverse;

				.msg-text {
					margin-top: 30rpx;
					margin-right: 16rpx;
					background-color: rgba(238, 0, 19, 1);
					border-radius: 20rpx 0rpx 20rpx 20rpx;
					color: #fff;
					// border-radius: 2rpx;
					box-shadow: 0rpx 5rpx 15rpx 0rpx rgba(0, 0, 0, 0.18);
					word-break: break-all;
				}

				.ms-img {
					margin-right: 16rpx;
				}
			}
		}
	}

	.user-name {
		margin-top: 5rpx;
		text-align: center;
		font-size: 20rpx;
		width: 60rpx;
		overflow: hidden;
		/* #ifndef APP-NVUE */
		white-space: nowrap;
		text-overflow: ellipsis;
		/* #endif */
		/* #ifdef APP-NVUE */
		lines: 1;
		text-overflow: ellipsis;
		/* #endif */
	}

	.nav-container {
		position: sticky;
		z-index: 999;
		height: 40rpx;
	}
</style>
